var express = require('express');
var router = express.Router();
const path = require('path');
const shortid = require('shortid');
const AccountModel = require('../../model/accountModel');
const moment = require('moment');
const checkLoginMiddleware = require('../../middleware/checkLoginMiddleware');
const { error } = require('console');


router.get('/', (req, res) => {
  res.redirect('/account');
})

//生成账本路由
router.get('/account', checkLoginMiddleware, function (req, res, next) {
  // let accounts = db.get('account').value();

  let accounts = AccountModel.find().sort({ date: -1 }).exec();
  accounts.then((data) => {

    res.render('list', { accounts: data, moment: moment });
  });

});

//生成添加账本路由
router.get('/account/add', checkLoginMiddleware, (req, res, next) => {
  res.render('add');
})

//提交表单
router.post('/account', checkLoginMiddleware, (req, res, next) => {

  req.body.date = new Date(Date.parse(req.body.date));

  let result = AccountModel.create({ ...req.body });

  result.then((data) => {

    res.render('success', {
      message: '添加成功...',
      url: '/account'

    })
  }).catch((error) => {
    res.render('error', { message: error.message, error });
  })
})

router.get('/account/:id', checkLoginMiddleware, (req, res, next) => {
  let id = req.params.id;


  let result = AccountModel.deleteOne({ _id: id });
  result.then(() => {

    res.render('success', {
      message: '删除成功',
      url: '/account',
    })
  })
  // db.get('account').remove({ id: id }).write();


})
module.exports = router;
